package com.qili.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.affaircase.AffairRecord;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.SupplierProjectPubNotice;
import com.qili.entity.supplier.dto.SupplierProjectDTO;
import com.qili.entity.supplier.dto.SupplierProjectPubNoticeDTO;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.SysUserWorkExperience;
import com.qili.service.SysUserService;
import com.qili.service.affairCase.AffairRecordService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.service.sys.SysUserWorkExperienceService;
import com.qili.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author zhaoyongke
 * @date 2021/4/6
 * @description
 */

@Controller
@Slf4j
@RequestMapping("/supplier/gspubnotice")
public class SupplierProjectPubNoticeController {


    @Autowired
    SupplierProjectPubNoticeService   supplierProjectPubNoticeService;

    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    SysUserService  sysUserService;
    @Autowired
    BaseCompanyService  baseCompanyService;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;

    @Autowired
    AffairRecordService affairRecordService;
    @Autowired
    SysUserWorkExperienceService userWorkExperienceService;

    /**
     * @Author:zhaoyongke
     * @Description: 结果公示
     * @Date:13:38 2021/3/13
     */
    @GetMapping(value = "index")
    @RequiresPermissions("supplier:projectGs")
    public String index(Model  model) {
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.YW_TYPE);
        model.addAttribute("projectTypeList", projectTypeList);
        return "projectManager/gsnoticeindex";
    }

    @GetMapping(value = "queryList")
    public String queryList(HttpServletRequest request) {
        return "projectManager/gsnoticeindex";
    }
    /**
     * @Author:zhaoyongke
     * @Description: 查看
     * @param noticeDTO
     * @param model
     * @param page
     * @param limit
     * @Date:22:28 2021/4/6
     */
    @ApiOperation(value = "/queryGsList", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "/queryGsList")
    @ResponseBody
    public ReType queryList(SupplierProjectPubNoticeDTO noticeDTO, Model model, String page, String limit) {
        ReType re = new ReType();


        Subject subject = SecurityUtils.getSubject();
        /**
         * 2022年3月18日17:08:25
         *
         * 查看所有项目：
         *  系统管理员、市场部经理、供方合同负责人
         *
         * 按照部门区分：
         *  市场人员、发布审核人、中标审核人、供需经理
         *  scry   pucheckper  zbCheckPerson  gxjl
         */
        if ( subject.hasRole("scry") || subject.hasRole("gxjl") || subject.hasRole("zbCheckPerson") || subject.hasRole("pucheckper")){
            // 获取当前登录人的用户信息
            SysUser user = sysUserService.selectByPrimaryKey(CommonUtil.getUserId());
            // 根据公司查询
            noticeDTO.setCompanyName(user.getCompanyName());
            // 根据部门查询
            // 获取发布人的部门 【市场一部 || 分支管理部】
            SysUserWorkExperience nowWork = new SysUserWorkExperience();
            nowWork.setSuId(user.getId());
            nowWork.setIfNow("1");
            SysUserWorkExperience experience =null;
            List<SysUserWorkExperience> selectlist = userWorkExperienceService.select(nowWork);
            if(!CollectionUtils.isEmpty(selectlist)){
                experience=selectlist.get(0);
                noticeDTO.setDeptName(experience.getDeptCode());
            }else{
                noticeDTO.setDeptName("1111");
            }
        }

        Page<SupplierProjectPubNoticeDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<SupplierProjectPubNoticeDTO> list = supplierProjectPubNoticeService.selectGsList(noticeDTO);
        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(list);
        return re;

    }
    /**
     * @Author:zhaoyongke
     * @Description: 发布结果公示---需方发布
     * @param model
     * @param dto
     * @Date:22:40 2021/4/6
     */
    @GetMapping(value = "pushGsDetail")
    public String pushGsDetail(Model model,SupplierProjectDTO dto) {
        String supProjectId = dto.getSupProjectId();
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        //中标单位
        String zbCompany = project.getZbCompany();
        String comType = project.getZbComType();
        //中标人
        String zbBy = project.getZbBy();
        String publish_by = project.getPublishBy();
        // 发布单位
        String pushcompany = getFbdwByUser(publish_by);
        //中标单位
        String zbcompany = getZbdwByCompanyId(zbCompany,comType);
        SysUser sysUser = sysUserService.selectByPrimaryKey(zbBy);
        //中标人
        String zbuserName = sysUser.getRealName();
        // 获取选择的项目经理的信息
        getUserJlZxJcManage(supProjectId,model);
        model.addAttribute("zbusername",zbuserName);
        model.addAttribute("zbcompany",zbcompany);
        model.addAttribute("pushcompany",pushcompany);
        model.addAttribute("supProjectId",supProjectId);
        model.addAttribute("project",project);
        return "projectManager/pushGsDetail";
    }
    /**
     * @Author:zhaoyongke
     * @Description: 获取中标得项目经理名称
     * @param supProjectId
     * @param model
     * @Date:11:32 2021/9/6
     */
    public   void   getUserJlZxJcManage(String supProjectId,Model  model ) {

        //2021 0906  获取项目经理等信息
        SupplierProjectAccept notdto = new SupplierProjectAccept();
        notdto.setSupProjectId(supProjectId);
        notdto.setIsZb("1");
        List<SupplierProjectAccept> list = supplierProjectAcceptService.select(notdto);
        if (list != null) {
            if (list.size() > 0) {
                SupplierProjectAccept accept = list.get(0);
                if (accept != null) {
                    String jlManagerPerson = accept.getJlManagerPerson();
                    if (StringUtil.isNotBlank(jlManagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(jlManagerPerson);
                        if (sysUser1 != null) {
                            String jlmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if(StringUtil.isNotBlank(realName)){
                                model.addAttribute("jlmanagename",realName);
                            }else{
                                model.addAttribute("jlmanagename",jlmanagename);
                            }

                        }
                    }
                    String jcManagerPerson = accept.getJcManagerPerson();
                    if (StringUtil.isNotBlank(jcManagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(jcManagerPerson);
                        if (sysUser1 != null) {
                            String jcmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if(StringUtil.isNotBlank(realName)){
                                model.addAttribute("jcmanagename",realName);
                            }else{
                                model.addAttribute("jcmanagename",jcmanagename);
                            }


                        }
                    }
                    String zxManagerPerson = accept.getZxManagerPerson();
                    if (StringUtil.isNotBlank(zxManagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(zxManagerPerson);
                        if (sysUser1 != null) {
                            String zxmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if(StringUtil.isNotBlank(realName)){
                                model.addAttribute("zxmanagename",realName);
                            }else{
                                model.addAttribute("zxmanagename",zxmanagename);
                            }

                        }
                    }
                    String qtMagagerPerson = accept.getQtMagagerPerson();
                    if (StringUtil.isNotBlank(qtMagagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(qtMagagerPerson);
                        if (sysUser1 != null) {
                            String qtmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if(StringUtil.isNotBlank(realName)){
                                model.addAttribute("qtmanagename",realName);
                            }else{
                                model.addAttribute("qtmanagename",qtmanagename);
                            }

                        }
                    }
                }
                //

            }
        }
    }




    /**
     * @Author:zhaoyongke
     * @Description: 发布结果公示---需方发布
     * @param model
     * @param dto
     * @Date:22:40 2021/4/6
     */
    @GetMapping(value = "viewPushGsDetail")
    public String viewPushGsDetail(Model model,SupplierProjectDTO dto) {
        String supProjectId = dto.getSupProjectId();
        SupplierProject project =  supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        SupplierProjectPubNoticeDTO noticedto=new SupplierProjectPubNoticeDTO();
        noticedto.setSupProjectId(supProjectId);
        List<SupplierProjectPubNotice>  list  =  supplierProjectPubNoticeService.select(noticedto);
        SupplierProjectPubNotice pubNotice = list.get(0);
        //中标单位
        String zbCompany = pubNotice.getZbCompany();
        String comType = pubNotice.getZbComType();
        //中标人
        String zbBy = pubNotice.getZbBy();
        String publish_by = project.getPublishBy();
        // 发布单位
        String pushcompany = getFbdwByUser(publish_by);
        //中标单位
        String zbcompany = getZbdwByCompanyId(zbCompany,comType);
        SysUser sysUser = sysUserService.selectByPrimaryKey(zbBy);
        //中标人
        String zbuserName = sysUser.getRealName();
        getUserJlZxJcManage( supProjectId, model );

        model.addAttribute("zbusername",zbuserName);
        model.addAttribute("zbcompany",zbcompany);
        model.addAttribute("pushcompany",pushcompany);
        model.addAttribute("supProjectId",supProjectId);
        model.addAttribute("project",project);
        model.addAttribute("pubNotice",pubNotice);
        String remark = project.getRemark();
        String publishType = project.getPublishType();
        String isConfirm = project.getIsConfirm();
        //
        if(!"001".equals(publishType)){
            model.addAttribute("remark",remark);
        }else  if("001".equals(publishType)){
            if("3".equals(isConfirm)){
                //
                AffairRecord recordquerycheck = new AffairRecord();
                recordquerycheck.setYwType("000");
                recordquerycheck.setYwId(supProjectId);
                List<AffairRecord> selectcheck = affairRecordService.select(recordquerycheck);
                if(selectcheck!=null){
                    model.addAttribute("selectcheck",selectcheck);
                }

            }


        }
        return "projectManager/viewPushGsDetail";
    }




    /**
     * @Author:zhaoyongke
     * @Description: 获取发布单位
     * @param userId
     * @Date:10:24 2021/4/7
     */
    public   String  getFbdwByUser(String  userId){
        String companyName="";
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        String source = sysUser.getSource();
        if("001".equals(source)){
            // 正中人员
            String companyId= sysUser.getCompanyName();
            BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(companyId);
            companyName= baseCompany.getBcName();
        }else{
            companyName=sysUser.getCompanyName();
        }
        return companyName;

    }

    /**
     * @Author:zhaoyongke
     * @Description: 获取中标单位
     * @param companyId
     * @param comtype
     * @Date:10:31 2021/4/7
     */
    public   String  getZbdwByCompanyId(String  companyId,String comtype){
        String companyName="";
        if("001".equals(comtype)){
            //001 保存的是公司表Id
            BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(companyId);
            companyName= baseCompany.getBcName();
        }else{
            SysUser sysUser = sysUserService.selectByPrimaryKey(companyId);
            companyName=sysUser.getCompanyName();
        }
        return companyName;

    }


    /**
     * @Author:zhaoyongke
     * @Description: 删除临时文件
     * @Date:18:39 2021/4/5
     */
    @RequestMapping(value = "/addPubNotice", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil addPubNotice(SupplierProjectPubNoticeDTO  dto) {
        JsonUtil re = new JsonUtil();
        try {
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(dto.getSupProjectId());
            SupplierProjectPubNotice  pubNotice=new SupplierProjectPubNotice();
            pubNotice.setSupProjectId(dto.getSupProjectId());
            pubNotice.setPubComType(project.getPubComType());
            pubNotice.setPubCompany(project.getPublishCompany());
            pubNotice.setStartDate(dto.getStartDate());
            pubNotice.setEndDate(dto.getEndDate());
            String  status="";
            Date jdStarDate = DateUtil.parseDate(dto.getStartDate(), "yyyy-MM-dd HH:mm");
            Date jdEndDate = DateUtil.parseDate(dto.getEndDate(), "yyyy-MM-dd HH:mm");
            Date currdate = new Date();
            if (currdate.before(jdStarDate)) {
                status = "0";
            } else if (currdate.after(jdEndDate)) {
                status = "2";
            }else {
                status = "1";
            }
            /**
             * 公示状态 0  未公示 1 公示中  2 结束
             */
            pubNotice.setGsStatus(status);
            // 中标人
            pubNotice.setZbBy(project.getZbBy());
            pubNotice.setSupProjectId(project.getSupProjectId());
            pubNotice.setZbComType(project.getZbComType());
            pubNotice.setZbCompany(project.getZbCompany());
            supplierProjectPubNoticeService.insertSelective(pubNotice);
            project.setIsGs("1");
            supplierProjectManagerService.updateByPrimaryKey(project);
            re.setMsg("发布成功");
            re.setFlag(true);
        } catch (
                Exception e) {
            re.setMsg("发布失败!" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }

    /**
     * 查询项目是否公示
     * @param model
     * @param dto
     * @return
     */
    @RequestMapping("publicity")
    @ResponseBody
    public JsonUtil publicity(Model model,SupplierProjectDTO dto) {
        JsonUtil json=new JsonUtil();
        SupplierProjectPubNoticeDTO noticedto=new SupplierProjectPubNoticeDTO();
        noticedto.setSupProjectId(dto.getSupProjectId());
        List<SupplierProjectPubNotice>  list  =  supplierProjectPubNoticeService.select(noticedto);
        if(list!=null&&list.size()>0){
            json.setFlag(true);
            return json;
        }
        json.setFlag(false);
        json.setMsg("项目未公示");
        return json;
    }
}
